package com.tengju.bff.interfaces.manage.crm.activity.facade.assembler;//package com.tengju.bff.interfaces.manage.crm.activity.facade.assembler;

import com.tengju.bff.interfaces.manage.crm.activity.form.ActivityBaseQuery;
import com.tengju.bff.interfaces.manage.crm.activity.form.ActivityDirectorQuery;
import com.tengju.bff.interfaces.manage.crm.activity.form.ActivityTeamQuery;
import com.tengju.data.domain.model.analysis.Meta;
import com.tengju.data.domain.model.cqrs.CrmActivityAnalysisQO;
import com.tengju.data.domain.model.cqrs.DataActivitySubjectType;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.motivation.domain.model.activity.Activity;
import com.tengju.motivation.domain.model.activity.ActivityTargetType;
import com.tengju.motivation.domain.model.activity.LimitSolution;
import com.tengju.motivation.domain.model.activity.UserLevel;
import com.tengju.motivation.domain.model.goods.GoodsType;
import com.tengju.user.domain.model.user.UserIdCode;
import com.tengju.user.domain.model.user.UserInfo;
import com.tengju.user.domain.shared.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author chenhang
 * @Date 2021/10/14
 */
public class QueryAssembler {

    public static CrmActivityAnalysisQO assemblerToBaseQuery(ActivityBaseQuery query, Activity activity, List<UserIdCode> genSecIdCodes) {
        if (query == null) {
            return null;
        }
        CrmActivityAnalysisQO qo = new CrmActivityAnalysisQO();
        qo.setActivityId(query.getActivityId());
        qo.setActivitySubjectId(query.getActivitySubjectId());
        if (!CollectionUtils.isEmpty(genSecIdCodes)) {
            List<Long> genSecIdCodeVals = genSecIdCodes.stream().map(UserIdCode::getValue).collect(Collectors.toList());
            qo.setGenSecIdCodeList(genSecIdCodeVals);
        }
        if (activity != null) {
            if (activity.getExtraInfo() != null) {
                Activity.ActivityExtraInfo extraInfo = activity.getExtraInfo();
                qo.setCrowdId(extraInfo.getIntentionCrowdId() != null ? extraInfo.getIntentionCrowdId().getValue() : 0L);
                qo.setActivityType(extraInfo.getActivityType().getVal());

                // 用户增长活动
                if (ActivityTargetType.GROWTH.equals(extraInfo.getTargetType())) {
                    qo.setActivitySubjectType(DataActivitySubjectType.GIFT.getCode());
                    //受众等级
                    UserLevel targetGrownUserLevel = extraInfo.getTargetGrownUserLevel();
                    if (targetGrownUserLevel == null) {
                        throw new BizException("活动受众等级缺失：" + activity.getActivityId().getValue());
                    }
                    String activityLimitLevelStr = Arrays.stream(UserLevel.values())
                            .filter(v -> v.isLower(targetGrownUserLevel))
                            .map(v -> v.getVal() + "")
                            .collect(Collectors.joining(","));
                    qo.setActivityLimitLevelStr(activityLimitLevelStr);

                    // 活动主体
                    qo.setActivitySubjectId(targetGrownUserLevel.getVal());

                // 销售活动
                } else if (ActivityTargetType.SALE.equals(extraInfo.getTargetType())) {
                    //受众等级
                    if (CollectionUtils.isEmpty(extraInfo.getLimitCustomerLevel())) {
                        throw new BizException("活动受众等级缺失：" + activity.getActivityId().getValue());
                    }
                    if (!CollectionUtils.isEmpty(extraInfo.getLimitCustomerLevel())) {
                        String activityLimitLevelStr = extraInfo.getLimitCustomerLevel().stream()
                                .map(v -> v.getVal() + "")
                                .collect(Collectors.joining(","));
                        qo.setActivityLimitLevelStr(activityLimitLevelStr);
                    }

                    // 活动主体
                    Activity.ActivityExtraInfo.LimitGoods limitGoods = extraInfo.getLimitGoods();
                    if (limitGoods == null) {
                        throw new BizException("活动主体类型缺失：" + activity.getActivityId().getValue());
                    }
                    LimitSolution activityLimitSolution = limitGoods.getLimitSolution();
                    if (LimitSolution.NONE.equals(activityLimitSolution)) {
                        qo.setActivitySubjectType(DataActivitySubjectType.BRAND.getCode());
                    } else {
                        GoodsType limitGoodsType = limitGoods.getLimitGoodsType();
                        if (GoodsType.SPU.equals(limitGoodsType)) {
                            qo.setActivitySubjectType(DataActivitySubjectType.SPU.getCode());
                        } else if (GoodsType.BRAND.equals(limitGoodsType)) {
                            qo.setActivitySubjectType(DataActivitySubjectType.BRAND.getCode());
                        } else {
                            throw new BizException("不支持的活动主体类型：" + activity.getActivityId().getValue());
                        }
                    }
                } else {
                    throw new BizException("不支持的活动类型：" + activity.getActivityId().getValue());
                }
            }
            LocalDateTime now = LocalDateTime.now();
            qo.setActivityEndDate(activity.getEndTime().toLocalDate().toString());
            qo.setActivityStartDate(activity.getStartTime().toLocalDate().toString());
            qo.setQueryStartDate(now.minusDays(1).toLocalDate().toString());
            qo.setQueryEndDate(activity.getEndTime().toLocalDate().toString());
            if (now.isAfter(activity.getEndTime())) {
                qo.setQueryStartDate(activity.getEndTime().toLocalDate().toString());
            }

        }
        return qo;
    }

    public static CrmActivityAnalysisQO assemblerToQuery(ActivityTeamQuery query, Activity activity, Meta meta, UserInfo userInfo, UserInfo dominationUserInfo, List<UserIdCode> genSecIdCodes) {
        CrmActivityAnalysisQO qo = assemblerToBaseQuery(query, activity,genSecIdCodes);
        qo.setUserRole(query.getUserRole().name());
        qo.setIdCode(query.getIdCode());
        qo.setPageSize(query.getPageSize());
        Integer offset = Math.max((query.getPageIndex() - 1) * query.getPageSize(),0);
        qo.setOffset(offset);
        if (meta != null) {
            qo.setOrderKey(meta.getOrderKey());
            qo.setOrderType(query.getOrderType());
        }
        if (userInfo != null) {
            qo.setIdCode(userInfo.getIdCode().getValue());
            qo.setStarLevel(userInfo.getStarLevel());
        }
        if (dominationUserInfo != null) {
            qo.setDominationIdCode(dominationUserInfo.getIdCode().getValue());
            qo.setDominationStarLevel(dominationUserInfo.getStarLevel());
        }
        return qo;
    }

    public static CrmActivityAnalysisQO assemblerToQuery(ActivityDirectorQuery query, Activity activity, Meta meta, String filterDepartmentIds, List<UserIdCode> genSecIdCodes) {
        CrmActivityAnalysisQO qo = assemblerToBaseQuery(query, activity,genSecIdCodes);
        qo.setDepartmentId(query.getDepartmentId());
        qo.setChiefId(query.getSsoUserId());
        qo.setPageSize(query.getPageSize());
        Integer offset = Math.max((query.getPageIndex() - 1) * query.getPageSize(),0);
        qo.setOffset(offset);
        if (meta != null) {
            qo.setOrderKey(meta.getOrderKey());
            qo.setOrderType(query.getOrderType());
        }
        if (StringUtils.isNotBlank(filterDepartmentIds)) {
            List<Long> departmentIdList = Stream.of(filterDepartmentIds.split(","))
                    .map(CastUtil::castLong)
                    .collect(Collectors.toList());
            qo.setDepartmentIdList(departmentIdList);
        }
        return qo;
    }
}